package com.jingdianjichi.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.application.convert.AuthRolePermissionDTOConverter;
import com.jingdianjichi.auth.application.dto.AuthRolePermissionDTO;
import com.jingdianjichi.auth.entity.Result;
import com.jingdianjichi.auth.domain.entity.AuthRolePermissionBO;
import com.jingdianjichi.auth.domain.service.AuthRolePermissionDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 角色DTO
 */
@RestController
@RequestMapping("/rolePermission")
@Slf4j
public class RolePermissionController {
    @Resource
    private AuthRolePermissionDomainService rolePermissionDomainService;

    /**
     * 新增角色权限关系表
     */
    @RequestMapping("/add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO rolePermissionDTO){
        try {
            if (log.isInfoEnabled()){
                log.info("RolePermissionController.add.dto:{}", JSON.toJSONString(rolePermissionDTO));
            }

            //参数校验
            Preconditions.checkArgument(!CollectionUtils.isEmpty(rolePermissionDTO.getPermissionIdList()),"权限id不能是空的");
            Preconditions.checkNotNull(rolePermissionDTO.getRoleId(),"角色id不能是空的");

            AuthRolePermissionBO rolePermissionBO=AuthRolePermissionDTOConverter.INSTANCE.convertDTOtoBO(rolePermissionDTO);

            Boolean result=rolePermissionDomainService.add(rolePermissionBO);

            return Result.ok(result);

        }catch (Exception e){
            log.error("RolePermissionController.add.error:{}",e.getMessage(),e);

            return Result.fail("角色权限关联失败");
        }
    }

}
